/**
 * 测试热门服务功能
 * 验证首页热门服务从数据库动态获取
 */

// 测试获取热门服务
async function testGetHotServices() {
  try {
    console.log('🚀 测试获取热门服务...')
    
    // 1. 测试云函数 getHotServices
    console.log('\n📡 调用 getHotServices 云函数...')
    const result = await wx.cloud.callFunction({
      name: 'serviceManager',
      data: {
        action: 'getHotServices',
        limit: 6
      }
    })
    
    if (result.result.success) {
      const hotServices = result.result.data
      console.log('✅ 获取热门服务成功')
      console.log(`📊 热门服务数量: ${hotServices.length}`)
      
      hotServices.forEach((service, index) => {
        console.log(`${index + 1}. ${service.title}`)
        console.log(`   分类: ${service.categoryInfo?.name || service.category}`)
        console.log(`   价格: ¥${service.price}/${service.unit}`)
        console.log(`   评分: ${service.rating}`)
        console.log(`   标签: ${service.badge}`)
        console.log(`   图片: ${service.image ? '✅' : '❌'}`)
        console.log('')
      })
      
      return hotServices
    } else {
      console.error('❌ 获取热门服务失败:', result.result.error)
      return null
    }
    
  } catch (error) {
    console.error('❌ 测试过程中发生错误:', error)
    return null
  }
}

// 测试不同数量限制
async function testHotServicesWithDifferentLimits() {
  try {
    console.log('\n🔢 测试不同数量限制...')
    
    const limits = [3, 6, 10]
    
    for (const limit of limits) {
      console.log(`\n📊 测试限制数量: ${limit}`)
      
      const result = await wx.cloud.callFunction({
        name: 'serviceManager',
        data: {
          action: 'getHotServices',
          limit: limit
        }
      })
      
      if (result.result.success) {
        console.log(`✅ 返回 ${result.result.data.length} 个热门服务`)
      } else {
        console.log(`❌ 获取失败: ${result.result.error}`)
      }
    }
    
  } catch (error) {
    console.error('❌ 测试不同限制时发生错误:', error)
  }
}

// 验证热门服务数据质量
async function validateHotServicesQuality() {
  try {
    console.log('\n🔍 验证热门服务数据质量...')
    
    const result = await wx.cloud.callFunction({
      name: 'serviceManager',
      data: {
        action: 'getHotServices',
        limit: 10
      }
    })
    
    if (result.result.success) {
      const hotServices = result.result.data
      let qualityScore = 0
      let totalChecks = 0
      
      console.log('📋 数据质量检查:')
      
      hotServices.forEach((service, index) => {
        console.log(`\n${index + 1}. ${service.title}:`)
        
        // 检查必要字段
        const checks = [
          { name: '标题', value: service.title, required: true },
          { name: '描述', value: service.description, required: true },
          { name: '图片', value: service.image, required: false },
          { name: '价格', value: service.price, required: true },
          { name: '单位', value: service.unit, required: true },
          { name: '评分', value: service.rating, required: true },
          { name: '分类', value: service.category, required: true },
          { name: '分类信息', value: service.categoryInfo, required: false }
        ]
        
        checks.forEach(check => {
          const hasValue = check.value !== undefined && check.value !== null && check.value !== ''
          const status = hasValue ? '✅' : (check.required ? '❌' : '⚠️')
          console.log(`   ${status} ${check.name}: ${hasValue ? '有值' : '缺失'}`)
          
          if (check.required) {
            totalChecks++
            if (hasValue) qualityScore++
          }
        })
        
        // 检查评分是否合理
        const rating = parseFloat(service.rating)
        if (rating >= 4.0) {
          console.log(`   ✅ 评分优秀: ${rating}`)
          qualityScore++
        } else {
          console.log(`   ⚠️ 评分较低: ${rating}`)
        }
        totalChecks++
      })
      
      const qualityPercentage = Math.round((qualityScore / totalChecks) * 100)
      console.log(`\n📊 数据质量评分: ${qualityScore}/${totalChecks} (${qualityPercentage}%)`)
      
      if (qualityPercentage >= 90) {
        console.log('🎉 数据质量优秀!')
      } else if (qualityPercentage >= 70) {
        console.log('👍 数据质量良好')
      } else {
        console.log('⚠️ 数据质量需要改善')
      }
      
    } else {
      console.error('❌ 获取热门服务失败:', result.result.error)
    }
    
  } catch (error) {
    console.error('❌ 验证数据质量时发生错误:', error)
  }
}

// 对比新旧方法的性能
async function compareOldAndNewMethods() {
  try {
    console.log('\n⚡ 对比新旧方法性能...')
    
    // 测试新方法 (getHotServices)
    console.log('\n🆕 测试新方法 (getHotServices):')
    const startTimeNew = Date.now()
    
    const newResult = await wx.cloud.callFunction({
      name: 'serviceManager',
      data: {
        action: 'getHotServices',
        limit: 6
      }
    })
    
    const endTimeNew = Date.now()
    const newMethodTime = endTimeNew - startTimeNew
    
    console.log(`⏱️ 新方法耗时: ${newMethodTime}ms`)
    console.log(`📊 返回数据量: ${newResult.result.success ? newResult.result.data.length : 0}`)
    
    // 测试旧方法 (getAllServices + 客户端筛选)
    console.log('\n🔄 测试旧方法 (getAllServices + 筛选):')
    const startTimeOld = Date.now()
    
    const oldResult = await wx.cloud.callFunction({
      name: 'serviceManager',
      data: {
        action: 'getAllServices'
      }
    })
    
    let filteredCount = 0
    if (oldResult.result.success) {
      // 模拟客户端筛选逻辑
      const filtered = oldResult.result.data
        .filter(service => service.status === 'active' && service.image)
        .sort((a, b) => (b.rating || 0) - (a.rating || 0))
        .slice(0, 6)
      filteredCount = filtered.length
    }
    
    const endTimeOld = Date.now()
    const oldMethodTime = endTimeOld - startTimeOld
    
    console.log(`⏱️ 旧方法耗时: ${oldMethodTime}ms`)
    console.log(`📊 返回数据量: ${filteredCount}`)
    
    // 性能对比
    console.log('\n📈 性能对比结果:')
    const improvement = ((oldMethodTime - newMethodTime) / oldMethodTime * 100).toFixed(1)
    console.log(`🚀 新方法比旧方法快 ${improvement}%`)
    
    if (newMethodTime < oldMethodTime) {
      console.log('✅ 新方法性能更优!')
    } else {
      console.log('⚠️ 新方法性能有待优化')
    }
    
  } catch (error) {
    console.error('❌ 性能对比测试失败:', error)
  }
}

// 完整测试套件
async function runCompleteTest() {
  console.log('🧪 开始热门服务完整测试套件...\n')
  
  // 1. 基本功能测试
  const hotServices = await testGetHotServices()
  
  if (hotServices && hotServices.length > 0) {
    // 2. 不同限制测试
    await testHotServicesWithDifferentLimits()
    
    // 3. 数据质量验证
    await validateHotServicesQuality()
    
    // 4. 性能对比
    await compareOldAndNewMethods()
  }
  
  console.log('\n🎉 热门服务测试套件完成!')
}

// 导出测试函数
if (typeof module !== 'undefined' && module.exports) {
  module.exports = {
    testGetHotServices,
    testHotServicesWithDifferentLimits,
    validateHotServicesQuality,
    compareOldAndNewMethods,
    runCompleteTest
  }
}

// 如果在小程序环境中直接运行
if (typeof wx !== 'undefined') {
  console.log('热门服务测试函数已加载，可以调用:')
  console.log('- testGetHotServices() // 基本功能测试')
  console.log('- runCompleteTest() // 完整测试套件')
} 